<?php
namespace User\Controller;

use Common\Controller\HomebaseController;
use Think\Cache\Driver\Redis;
require_once './plugins/AliyunDysms/api_demo/SmsDemo.php';

class PublicController extends HomebaseController {
    
    // 用户头像api
	public function avatar(){
		$users_model=M("Users");
		$id=I("get.id",0,"intval");
		
		$find_user=$users_model->field('avatar')->where(array("id"=>$id))->find();
		
		$avatar=$find_user['avatar'];
		$avatar=preg_replace("/^avatar\//", '', $avatar);//2.2以后头像路径统一以avatar/开头
		$should_show_default=false;
		
		if(empty($avatar)){
			$should_show_default=true;
		}else{
			if(strpos($avatar,"http")===0){
				header("Location: $avatar");exit();
			}else{
				$avatar_dir=C("UPLOADPATH")."avatar/";
				$avatar=$avatar_dir.$avatar;
				if(file_exists($avatar)){
					$imageInfo = getimagesize($avatar);
					if ($imageInfo !== false) {
					    $fp=fopen($avatar,"r");
					    $file_size=filesize($avatar);
						$mime=$imageInfo['mime'];
						header("Content-type: $mime");
						header("Accept-Length:".$file_size);
						$buffer=1024*64;
						$file_count=0;
						//向浏览器返回数据
						while(!feof($fp) && $file_count<$file_size){
						    $file_content=fread($fp,$buffer);
						    $file_count+=$buffer;
						    echo $file_content;
						    flush();
						    ob_flush();
						}
						fclose($fp);
					}else{
						$should_show_default=true;
					}
				}else{
					$should_show_default=true;
				}
			}
		}
		
		if($should_show_default){
			$imageInfo = getimagesize("public/images/headicon.png");
			if ($imageInfo !== false) {
				$mime=$imageInfo['mime'];
				header("Content-type: $mime");
				echo file_get_contents("public/images/headicon.png");
			}
		}
		exit();
	}


    public function send_aliyun_sms()
    {
        $phone = I('phone');
        // 验证格式
        $preg_phone = '/^1[345678]\d{9}$/ims';
        if(!preg_match($preg_phone, $phone)){
            $this->error('请填写正确的手机号');exit;
        }

        $verify = I('verify');
        if ($verify) {
            if (!sp_check_verify_code($verify, false)) {
                $this->error('验证码错误');exit;
            }
        }

        $expire     = 15 * 60;
        $pre        = 'sms_code_';
        $key        = $pre . $phone;
        $redis      = Redis::getinstance();
        $old_code   = $redis->get($key);
        $ttl        = $redis->ttl($key);

        if ($old_code && $ttl > $expire / 2) {
            $this->success('验证码已发送');exit;
        }

        // 生成验证码
        $code = rand(100000, 999999);
        $redis->set($key, $code, $expire);

        // 发送短信
        $smsClass   = new \SmsDemo();
        $re         = $smsClass->sendSms($phone, $code);

        if ($re->Code == 'OK') {
            $this->success('验证码已发送!');
        } else {
            $this->error('验证码发送失败，请稍后再试');
        }
	}
}
